<?php

namespace app\admin\model;

use think\Db;
use think\Model;


class CategoryQuan extends Model
{


    // 表名
    protected $name = 'category_quan';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    //属性转换
    protected $type = [
        'id'              => 'integer',
        'category_id'     => 'integer',
        'user_id'         => 'integer',
        'order_id'        => 'integer',
        'quan_face_price' => 'float',
        'quan_balance'    => 'float',
        'quan_price'      => 'float',
    ];


    //创建数据事件,自动插入更新时间
    protected static function init()
    {
        CategoryQuan::event('before_insert', function ($categoryQuan) {
            $categoryQuan->create_time = date("Y-m-d H:i:s");
        });
        // CategoryQuan::event('before_update', function ($categoryQuan) {
        //     $categoryQuan->used_time = date("Y-m-d H:i:s");
        // });
    }


    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    //获取指定用户在指定门店的可用券
    public static function GetQuanList($user_id, $category_id)
    {
        // `quan_face_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '优惠券面值',
        // `quan_balance` decimal(10,2) DEFAULT '0.00' COMMENT '余额',
        // `quan_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '美团团购价',
        // `expire_time` datetime DEFAULT NULL COMMENT '优惠券过期时间',
        $quan_list = self::where(['user_id' => $user_id, 'category_id' => $category_id])
            //非锁定券
            ->where('is_lock', 0)
            ->where('expire_time', '>', date("Y-m-d H:i:s"))
            ->where('quan_balance', '>', 0)
            //字段quan_balance值必须小于字段quan_face_price值
            ->where('quan_balance', '<=', Db::raw('quan_face_price'))
            ->select();
        //如果没有记录，就返回0
        if (empty($quan_list)) {
            return [];
        }
        return $quan_list;
    }

    //优惠券余额变更
    public static function change(
        $quan_id,
        $user_id,
        $category_id,
        $amount,
        $remark
    ) {
        //根据条件查找优惠券
        $category_quan_info = self::where(['id' => $quan_id, 'user_id' => $user_id, 'category_id' => $category_id]
        )->find();
        //如果没有找到优惠券
        if (!$category_quan_info) {
            //抛出异常
            throw new \Exception("优惠券不存在");
        }

        //如果是扣款的情况
        if ($amount<0){
            //如果优惠券余额不足
            if ($category_quan_info->quan_balance < abs($amount)) {
                //抛出异常
                throw new \Exception("优惠券余额不足");
            }
        }
        //优惠券是否已过期
        if ($category_quan_info->expire_time < date("Y-m-d H:i:s")) {
            //抛出异常
            throw new \Exception("优惠券已过期,不能操作");
        }

        //是否锁定
        if ($category_quan_info->is_lock == 1) {
            //抛出异常
            throw new \Exception("此优惠券已锁定,不能使用");
        }


        $before = $category_quan_info->quan_balance;
        $after = $category_quan_info->quan_balance + $amount;


        //扣除优惠券余额
        $category_quan_info->quan_balance = $category_quan_info->quan_balance + $amount;
        //如果优惠券余额为0
        if ($category_quan_info->quan_balance == 0) {
            //优惠券已使用
            $category_quan_info->is_used = 1;

            $category_quan_info->used_time = date("Y-m-d H:i:s");
            // 设置优惠券过期时间
            // $category_quan_info->expire_time = date("Y-m-d H:i:s");
        }
        //保存
        $category_quan_info->save();


        //记录优惠券使用记录
        $categoryQuanLog = new UserCategoryQuanLog();
        $categoryQuanLog->user_id = $user_id;
        $categoryQuanLog->category_id = $category_id;
        $categoryQuanLog->quan_id = $category_quan_info->id;
        $categoryQuanLog->before = $before;
        $categoryQuanLog->money = $amount;
        $categoryQuanLog->after = $after;
        $categoryQuanLog->memo = $remark;
        $categoryQuanLog->createtime = time();
        $categoryQuanLog->save();
    }

    //优惠券是否锁定
    public static function isLock($quan_id)
    {
        //根据条件查找优惠券
        $category_quan_info = self::where(['id' => $quan_id])->find();
        //如果没有找到优惠券
        if (!$category_quan_info) {
            //抛出异常
            throw new \Exception("优惠券不存在");
        }
        return $category_quan_info->is_lock==1?true:false;
    }
    //锁定一张优惠券
    public static function lockQuan($quan_id)
    {
        //根据条件查找优惠券
        $category_quan_info = self::where(['id' => $quan_id])->find();
        //如果没有找到优惠券
        if (!$category_quan_info) {
            //抛出异常
            throw new \Exception("优惠券不存在");
        }

        //优惠券是否已过期
        if ($category_quan_info->expire_time < date("Y-m-d H:i:s")) {
            //抛出异常
            throw new \Exception("优惠券已过期");
        }

        $category_quan_info->is_lock = 1;
        $category_quan_info->lock_time = date("Y-m-d H:i:s");
        $category_quan_info->save();
    }

    //解锁一张优惠券
    public static function unLockQuan($quan_id)
    {
        //根据条件查找优惠券
        $category_quan_info = self::where(['id' => $quan_id])->find();
        //如果没有找到优惠券
        if (!$category_quan_info) {
            //抛出异常
            throw new \Exception("优惠券不存在");
        }

        $category_quan_info->is_lock = 0;
        $category_quan_info->lock_time = null;
        $category_quan_info->save();
    }


    //解锁锁定时间超过30分钟的所有优惠券
    public static function unlockExpireQuan()
    {
        //根据条件查找优惠券
        $category_quan_info = self::where(['is_lock' => 1])
            ->where('lock_time', '<', date("Y-m-d H:i:s", strtotime("-30 minutes")))
            ->select();
        foreach ($category_quan_info as $key => $value) {
            $value->is_lock = 0;
            $value->lock_time = null;
            $value->save();
        }
    }
}
